import axios from 'axios'
import i18n from '../i18n'
import router from '../router'
import loginService, { FETCH_USER_URL, LOGIN_URL } from '@/services/login-service'

const LANG_HEADER = 'Accept-Language'

export default function () {
  axios.interceptors.request.use(function (request) {
    request.headers[LANG_HEADER] = i18n.locale.locale.getName()
    return request
  })
  axios.interceptors.response.use(
    function (response) {
      return response
    },
    function (error) {
      if (error && error.response && error.response.status) {
        if (
          (error.response.status === 401 || error.response.status === 403) &&
          error.config.url !== FETCH_USER_URL && error.config.url !== LOGIN_URL
        ) {
          // 权限不足，强制跳转到 login 界面
          loginService.logout().then(() => {
            router.go(0)
          })
        } else {
          return Promise.reject(error)
        }
      }
    }
  )
}
